package weibo.service;

import java.io.IOException;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import weibo.database.TweetDB;
import weibo.model.TweetMod;

/**
 * Servlet implementation class queryalltweet
 */
@WebServlet("/queryalltweet")
public class queryalltweet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public queryalltweet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//doGet(request, response);
		response.setCharacterEncoding("utf8");
		String requestTypeString=request.getParameter("type");
		List<TweetMod> tweet=null;
		TweetDB db=null;
		JSONObject json=new JSONObject();
		if (requestTypeString==null){
			response.getWriter().append("request error");
			System.out.println("推文查询，无效的请求");
		}else if(requestTypeString.equals("new")){
			//查询最新的十条推文
			db=new TweetDB();
			tweet=db.QuesyNewTweet();
			json.put("tweet", tweet);
			response.getWriter().append(json.toJSONString());
			
		}else if(requestTypeString.equals("continue")){
			//查询某id之后的推文
			db=new TweetDB();
			int tweet_id=0; //请求的推文ID
			int len=10;//长度
			if (request.getParameter("tweet_id")!=null){
				tweet_id=Integer.parseInt(request.getParameter("tweet_id"));
			}
			if (request.getParameter("len")!=null){
				len=Integer.parseInt(request.getParameter("len"));
				if (len==0) len=10;
			}
			tweet=db.QueryAllTweent(tweet_id, len);
			json.put("tweet", tweet);
			response.getWriter().append(json.toJSONString());
			
		}else{
			System.out.println("推文查询，无效的请求 " + requestTypeString);
			response.getWriter().append("request error "+requestTypeString);
		}
		
	}

}
